Telegram Group & Telegram Channel
✔️ Задача. Что выведет на консоль этот пример на C#?


using System;
using System.Collections.Generic;

class Program
{
static void Main()
{
var funcs = new List<Func<int>>();

// Первая группа лямбд
for (int i = 0; i < 4; i++)
{
funcs.Add(() => i * i);
}

Console.Write("Squares: ");
foreach (var f in funcs)
Console.Write(f() + " ");

Console.WriteLine();

// Вторая группа лямбд с копией переменной
funcs.Clear();
for (int i = 0; i < 4; i++)
{
int j = i;
funcs.Add(() => j * j);
}

Console.Write("SquaresWithCopy: ");
foreach (var f in funcs)
Console.Write(f() + " ");
}
}

Ответ:
Squares: 16 16 16 16
SquaresWithCopy: 0 1 4 9

Объяснение
Первая группа лямбд
Лямбды захватывают переменную i по ссылке. К моменту, когда мы их вызываем в foreach, цикл уже завершился, поэтому i == 4. Каждая лямбда вычисляет 4 * 4 → 16.

Вторая группа лямбд
Внутри цикла для каждого значения i создаётся новая локальная переменная j, и лямбда захватывает именно её. При первой итерации j = 0, при второй j = 1 и т. д. Поэтому j * j даёт 0, 1, 4, 9 соответственно.

Такой приём (захват локальной копии переменной) позволяет избежать «одинообразного» результата и сохранить значение каждой итерации.
Please open Telegram to view this post
VIEW IN TELEGRAM



tg-me.com/csharp_ci/1346
Create:
Last Update:

✔️ Задача. Что выведет на консоль этот пример на C#?


using System;
using System.Collections.Generic;

class Program
{
static void Main()
{
var funcs = new List<Func<int>>();

// Первая группа лямбд
for (int i = 0; i < 4; i++)
{
funcs.Add(() => i * i);
}

Console.Write("Squares: ");
foreach (var f in funcs)
Console.Write(f() + " ");

Console.WriteLine();

// Вторая группа лямбд с копией переменной
funcs.Clear();
for (int i = 0; i < 4; i++)
{
int j = i;
funcs.Add(() => j * j);
}

Console.Write("SquaresWithCopy: ");
foreach (var f in funcs)
Console.Write(f() + " ");
}
}

Ответ:
Squares: 16 16 16 16
SquaresWithCopy: 0 1 4 9

Объяснение
Первая группа лямбд
Лямбды захватывают переменную i по ссылке. К моменту, когда мы их вызываем в foreach, цикл уже завершился, поэтому i == 4. Каждая лямбда вычисляет 4 * 4 → 16.

Вторая группа лямбд
Внутри цикла для каждого значения i создаётся новая локальная переменная j, и лямбда захватывает именно её. При первой итерации j = 0, при второй j = 1 и т. д. Поэтому j * j даёт 0, 1, 4, 9 соответственно.

Такой приём (захват локальной копии переменной) позволяет избежать «одинообразного» результата и сохранить значение каждой итерации.

BY C# (C Sharp) programming


Warning: Undefined variable $i in /var/www/tg-me/post.php on line 283

Share with your friend now:
tg-me.com/csharp_ci/1346

View MORE
Open in Telegram


C C Sharp programming Telegram | DID YOU KNOW?

Date: |

For some time, Mr. Durov and a few dozen staffers had no fixed headquarters, but rather traveled the world, setting up shop in one city after another, he told the Journal in 2016. The company now has its operational base in Dubai, though it says it doesn’t keep servers there.Mr. Durov maintains a yearslong friendship from his VK days with actor and tech investor Jared Leto, with whom he shares an ascetic lifestyle that eschews meat and alcohol.

The messaging service and social-media platform owes creditors roughly $700 million by the end of April, according to people briefed on the company’s plans and loan documents viewed by The Wall Street Journal. At the same time, Telegram Group Inc. must cover rising equipment and bandwidth expenses because of its rapid growth, despite going years without attempting to generate revenue.

C C Sharp programming from tw


Telegram C# (C Sharp) programming
FROM USA